<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="商品名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['commodityName', validatorRules.commodityName]" :disabled="true" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="制码数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['codeNum', validatorRules.codeNum]" :disabled="true"  ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="编码区间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['sectionNo', validatorRules.sectionNo]" :disabled="true" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="下载区间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['sectionNumber', validatorRules.sectionNumber]" placeholder="下载区间"  ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JSZip from 'jszip'
  import FileSaver from "file-saver"

  export default {
    name: 'QyCompanyForm',
    components: {
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          sectionNumber: {
            rules: [
              { required: true, message: '请输入区间编号!'},
              {validator:this.checkSectionNumber}
            ]
          }

        }
      }
    },
    computed: {

    },
    created () {

    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        record.sectionNumber =this.formatSectionNo(record);
        this.form.resetFields();
        this.model = Object.assign({}, record);
        console.log(this.model )
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'updateTime','commodityId','batchNo','codeNum','sectionNo','commodityName','sectionNumber',"id"))
        })
      },
      submitForm () {
        //这里开始下载
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
              if(!this.confirmLoading){
                this.downImg(values);
              }
          }
        });
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'updateTime','commodityId','batchNo','codeNum','sectionNo','commodityName','sectionNumber',"id"))
      },
      formatSectionNo(record){
        let codeNum = record.codeNum;
        return "1-"+codeNum;
      },checkSectionNumber(rule, value, callback){
        const form = this.form;
        //  只能输入0-24之间的数字，最多只允许两位小数
        if(value.indexOf("-")==-1||value.split("-").length!=2){
          callback('请输入正确格式的下载区间,例:1-200！');
        }else{
           let a = value.split("-")[0];
           let b = value.split("-")[1];
           let r = /^\+?[1-9][0-9]*$/;
           if(!r.test(a)||!r.test(b)){
             callback('请输入正确格式的下载区间,例:1-200！');
           }else{
             if(parseInt(a)>parseInt(b)){
               callback('起始编号不能大于终止编号');
             }else{
               if(parseInt(b)>this.model.codeNum){
                 callback('终止编号不能超过'+this.model.codeNum);
               }else{
                 callback();
               }
             }
           }
        }

      },downImg(values) {
        var that = this;

        var blogTitle = values.commodityName+values.sectionNumber;
        var zip = new JSZip();
        var imgs = zip.folder(blogTitle);
        var baseList = [];
        // 要下载图片的url
        var arr = [];
        // 下载后图片的文件名，个数应与arr对应
        var imgNameList = [];
        that.confirmLoading = true;

        //封装下载的
        var sNumber = values.sectionNumber;
        var a = parseInt(sNumber.split("-")[0]);
        var b = parseInt(sNumber.split("-")[1]);
        for(var c =a;c<=b;c++){
          let name = that.model.batchNo+this.formatZero(c,6);
          arr.push("https://smsytech.oss-cn-zhangjiakou.aliyuncs.com/syQrCode/"+that.model.id+"/"+name+".png");
          imgNameList.push(name);
        }


        for (var i = 0; i < arr.length; i++) {
          let image = new Image();
          // 解决跨域 Canvas 污染问题
          image.setAttribute('crossOrigin', 'anonymous');

          image.onload = function () {
            let canvas = document.createElement('canvas');
            canvas.width = image.width;
            canvas.height = image.height;

            let context = canvas.getContext('2d');
            context.drawImage(image, 0, 0, image.width, image.height);

            let url = canvas.toDataURL(); // 得到图片的base64编码数据
            canvas.toDataURL('image/png');

            baseList.push(url.substring(22));    // 去掉base64编码前的 data:image/png;base64,
            if (baseList.length === arr.length && baseList.length > 0) {
              for (let k = 0; k < baseList.length; k++) {
                imgs.file(imgNameList[k] + '.png', baseList[k], {base64: true})
              }
              zip.generateAsync({type: 'blob'}).then(function (content) {
                // see FileSaver.js
                FileSaver.saveAs(content, blogTitle + '.zip');
                that.confirmLoading = false;
                that.$emit('ok');
              }).fail(function(){
                that.confirmLoading = false;
              })
            }

          };
          image.src = arr[i];
        }

      },formatZero(num, len) {
        if(String(num).length > len) return num;
        return (Array(len).join(0) + num).slice(-len);
      }
    }
  }
</script>